package com.project.dao.impl;

import com.project.bean.CommentBean;
import com.project.bean.UserBean;
import com.project.dao.ICommentDao;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Repository
public class CommentDaoImpl extends BaseDao implements ICommentDao {
    @Override
    public void addComment(CommentBean comment) {
        this.setConnection();
        try {
            ps=con.prepareStatement("insert into t_comment(fk_userId,c_content,fk_commodityId)"+"values (?,?,?)");
            ps.setObject(1,comment.getUser().getId());
            ps.setObject(2,comment.getContent());
            ps.setObject(3,comment.getCommodity().getId());
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.close();
        }
    }

    @Override
    public List<CommentBean> findByCommodity(Integer commodityId) {
        List<CommentBean> list = new ArrayList<>();
        this.setConnection();
        try {
            ps=con.prepareStatement("select c.*,u.`u_nickName` from t_user u,t_comment c WHERE u.`pk_userId`=c.`fk_userId` " +
                    "AND c.`fk_commodityId`=?");
            ps.setObject(1,commodityId);
            rs=ps.executeQuery();
            while (rs.next()){
                CommentBean com=new CommentBean();
                com.setId(rs.getInt("pk_commentId"));
                com.setContent(rs.getString("c_content"));
                UserBean user = new UserBean();
                user.setNickName(rs.getString("u_nickName"));
                com.setUser(user);
                list.add(com);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            this.close();
        }
        return list;
    }
}
